//
//  MeViewController.m
//  HonlivApp
//
//  Created by admin on 2017/6/23.
//  Copyright © 2017年 honliv. All rights reserved.
//

#import "MeViewController.h"
#import "MeViewModel.h"
#import "CommonStaticCell.h"
#import "HeadInfoCell.h"
#import "CleanCell.h"
#import "PersonalFileViewController.h"
#import "HealthyFilesViewController.h"
#import "OuptPatientInfoViewController.h"
#import "InpatientViewController.h"
#import "HXTViewController.h"
#import "BSStaticTBCell.h"
#import "LoginController.h"
#import "MailDetailViewController.h"

#import "WJTouchID.h"
#import "TouchIDCell.h"

#define DeviceVersion [UIDevice currentDevice].systemVersion.floatValue
static NSString *const touchNotName = @"judgeTouchId";

@interface MeViewController ()<WJTouchIDDelegate>

@property (nonatomic,strong) MeViewModel *viewModel;
@property (nonatomic,strong) WJTouchID *touchID;
@property (nonatomic,strong) UIAlertController *touchIdHUD;

@property (nonatomic,strong) UISwitch *touchSwitch;
@property (nonatomic,assign) BOOL currentTouchID;
@property (nonatomic,strong) UIView *hideView;

@end

@implementation MeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的";

    WJTouchID *touchid = [[WJTouchID alloc]init];
    self.touchID = touchid;
    
    [self createHideView];
    
}

-(void)viewWillAppear:(BOOL)animated{
    extern NSString * touchId;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissTouchIdHUD) name:touchNotName object:nil];
}
-(void)dismissTouchIdHUD{
    [_touchIdHUD dismissViewControllerAnimated:YES completion:nil];
}
-(void)createHideView{
    if (_hideView == nil) {
        _hideView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
        _hideView.backgroundColor = [UIColor whiteColor];
        _hideView.hidden = YES;
        [self.view addSubview:_hideView];
    }
}
-(void)getDatasArray{
    [self getDatasArray:^(GetDatas handler) {
        _viewModel = [[MeViewModel alloc] init];
        [_viewModel getDatasArraySuccess:^{
            handler(_viewModel.datasArray);
        }];
    }];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        //个人档案
        PersonalFileViewController *personalV = [[PersonalFileViewController alloc] init];
        [self pushViewControllerTo:personalV];
    }else if (indexPath.section == 1){
        switch (indexPath.row) {
            case 0:{
                MailDetailViewController *mailV = [[MailDetailViewController alloc] init];
                mailV.title = @"企业邮箱";
                mailV.type = MailTypeTencent;
                [self pushViewControllerTo:mailV];
            }
                break;
            case 1:{
                HealthyFilesViewController *healthyV = [[HealthyFilesViewController alloc] init];
                [self pushViewControllerTo:healthyV];
            }
                break;
            case 2:{
                OuptPatientInfoViewController *outPatientV = [[OuptPatientInfoViewController alloc] init];
                [self pushViewControllerTo:outPatientV];
            }
                break;
            case 3:{
                InpatientViewController *inpatientV = [[InpatientViewController alloc] init];
                [self pushViewControllerTo:inpatientV];
            }
                break;
            case 4:{
                //宏信通
                HXTViewController *hxtVC  =[[HXTViewController alloc] init];
                [self pushViewControllerTo:hxtVC];
            }
                break;
            default:
                break;
        }
    }else if (indexPath.section == 3){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注销账号" message:@"注销账号将清除登录信息，确定要注销吗？" preferredStyle:UIAlertControllerStyleActionSheet];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //退出登录
            LoginController *loginC = [[LoginController alloc] init];
            [[LoginInfoTool sharedLoginInfoTool] clearLoginInfo];
            [NetWorker sharedNetWorker].isLogin = NO;
            [NetWorker sharedNetWorker].isTouchId = NO;
            [self presentViewController:loginC animated:YES completion:nil];

        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alert animated:YES completion:nil];
        
        }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 0){
        return 100;
    }
    return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return 15;
    }
    return 10;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *ID = nil;
    if (indexPath.section == 0) {
        ID = @"headId";
        HeadInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if (!cell) {
            cell = [[HeadInfoCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            [cell setHeadInfo];
        }
        return cell;
    }else  if(indexPath.section == 1){
        CommonStaticCell *cell = [CommonStaticCell cellWithTableView:tableView];
        cell.dic = self.datasArray[indexPath.section][indexPath.row];
        
        return cell;
    }else if(indexPath.section == 2){
        if (indexPath.row == 0) {
           
            TouchIDCell *cell = [TouchIDCell cellWithTableView:tableView];
            cell.dic = self.datasArray[indexPath.section][indexPath.row];
            self.touchSwitch = cell.touchSwitch;
            self.currentTouchID = [self.touchSwitch isOn] ? YES : NO;
            [cell touchSwitchOn:^{
                if (self.currentTouchID) {
                    [self setHideViewState:NO];
                    [_touchIdHUD dismissViewControllerAnimated:YES completion:nil];
                    [self.touchID startWJTouchIDWithMessage:WJNotice(@"按下HOME键验证指纹信息", @"The Custom Message") fallbackTitle:WJNotice(@"输入密码", @"Fallback Title") delegate:self];
                }else{
                    // 实例化本地身份验证上下文
                    LAContext *context= [[LAContext alloc] init];
                    
                    // 判断是否支持指纹识别
                    if (DeviceVersion > 8.0 && [context canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:nil]) {
                        [self.touchSwitch setOn:YES];
                        self.currentTouchID = YES;
                        [NetWorker sharedNetWorker].isTouchId = YES;
                    }else{
                        [self.touchSwitch setOn:NO];
                        self.currentTouchID = NO;
                        [NetWorker sharedNetWorker].isTouchId = YES;
                        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"抱歉，您的iPhone暂不支持指纹解锁" preferredStyle:UIAlertControllerStyleAlert];
                        [self presentViewController:alert animated:YES completion:nil];
                        [self performSelector:@selector(dismissAlertC) withObject:nil afterDelay:1.0];
                    }
                }
                
            }];
            return cell;

        }
        CleanCell *cell = [CleanCell cellWithTableView:tableView];
        cell.dic = self.datasArray[indexPath.section][indexPath.row];
        return cell;
    }else{
        BSStaticTBCell *cell = [BSStaticTBCell cellWithTableView:tableView];
        NSDictionary *dic = self.datasArray[indexPath.section][indexPath.row];
        cell.title = dic[@"title"];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
        return cell;
    }
    
    return nil;

}
-(void)dismissAlertC{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  TouchID验证成功
 *
 *  (English Comments) Authentication Successul  Authorize Success
 */
- (void) WJTouchIDAuthorizeSuccess {
    [self.touchSwitch setOn:!self.currentTouchID];
    [NetWorker sharedNetWorker].isTouchId = !self.currentTouchID;
    self.currentTouchID = !self.currentTouchID;
    [self setHideViewState:YES];
    [[NetWorker sharedNetWorker] setLoginTime];
}

/**
 *  TouchID验证失败
 *
 *  (English Comments) Authentication Failure
 */
- (void) WJTouchIDAuthorizeFailure {
    [NetWorker sharedNetWorker].isTouchId = self.currentTouchID;
    [self.touchSwitch setOn:self.currentTouchID];
    [self showInputPWDHUD];
}
/**
 *  取消TouchID验证 (用户点击了取消)
 *
 *  (English Comments) Authentication was canceled by user (e.g. tapped Cancel button).
 */
- (void) WJTouchIDAuthorizeErrorUserCancel {
    [NetWorker sharedNetWorker].isTouchId = self.currentTouchID;
    [self.touchSwitch setOn:self.currentTouchID];
    [self showInputPWDHUD];
}

/**
 *  在TouchID对话框中点击输入密码按钮
 *
 *  (English Comments) User tapped the fallback button
 */
- (void) WJTouchIDAuthorizeErrorUserFallback {
    [NetWorker sharedNetWorker].isTouchId = self.currentTouchID;
    [self.touchSwitch setOn:self.currentTouchID];
    [self showInputPWDHUD];
}

/**
 *  在验证的TouchID的过程中被系统取消 例如突然来电话、按了Home键、锁屏...
 *
 *  (English Comments) Authentication was canceled by system (e.g. another application went to foreground).
 */
- (void) WJTouchIDAuthorizeErrorSystemCancel {
    [NetWorker sharedNetWorker].isTouchId = self.currentTouchID;
    [self.touchSwitch setOn:self.currentTouchID];
    [_touchIdHUD dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  无法启用TouchID,设备没有设置密码
 *
 *  (English Comments) Authentication could not start, because passcode is not set on the device.
 */
- (void) WJTouchIDAuthorizeErrorPasscodeNotSet {
    [NetWorker sharedNetWorker].isTouchId = self.currentTouchID;
    [self.touchSwitch setOn:NO];
}

/**
 *  设备没有录入TouchID,无法启用TouchID
 *
 *  (English Comments) Authentication could not start, because Touch ID has no enrolled fingers
 */
- (void) WJTouchIDAuthorizeErrorTouchIDNotEnrolled {
    [NetWorker sharedNetWorker].isTouchId = self.currentTouchID;
    [self.touchSwitch setOn:NO];
}

/**
 *  该设备的TouchID无效
 *
 *  (English Comments) Authentication could not start, because Touch ID is not available on the device.
 */
- (void) WJTouchIDAuthorizeErrorTouchIDNotAvailable {
    
    [self.touchSwitch setOn:NO];
}

/**
 *  多次连续使用Touch ID失败，Touch ID被锁，需要用户输入密码解锁
 *
 *  (English Comments) Authentication was not successful, because there were too many failed Touch ID attempts and Touch ID is now locked. Passcode is required to unlock Touch ID, e.g. evaluating LAPolicyDeviceOwnerAuthenticationWithBiometrics will ask for passcode as a prerequisite.
 *
 */
- (void) WJTouchIDAuthorizeLAErrorTouchIDLockout {
    [NetWorker sharedNetWorker].isTouchId = self.currentTouchID;
    [self.touchSwitch setOn:self.currentTouchID];
    [self showInputPWDHUD];
}

/**
 *  当前软件被挂起取消了授权(如突然来了电话,应用进入前台)
 *
 *  (English Comments) Authentication was canceled by application (e.g. invalidate was called while authentication was inprogress).
 *
 */
- (void) WJTouchIDAuthorizeLAErrorAppCancel {
    [NetWorker sharedNetWorker].isTouchId = self.currentTouchID;
    [self.touchSwitch setOn:self.currentTouchID];
    [self setHideViewState:YES];
    [_touchIdHUD dismissViewControllerAnimated:YES completion:nil];
}

/**
 *  当前软件被挂起取消了授权 (授权过程中,LAContext对象被释)
 *
 *  (English Comments) LAContext passed to this call has been previously invalidated.
 */
- (void) WJTouchIDAuthorizeLAErrorInvalidContext {
    [NetWorker sharedNetWorker].isTouchId = self.currentTouchID;
    [self.touchSwitch setOn:self.currentTouchID];
    [self setHideViewState:YES];
    [_touchIdHUD dismissViewControllerAnimated:YES completion:nil];
}
/**
 *  当前设备不支持指纹识别
 *
 *  (English Comments) The current device does not support fingerprint identification
 */
-(void)WJTouchIDIsNotSupport {
    [self.touchSwitch setOn:NO];
}


//弹出输入密码的提示框
-(void)showInputPWDHUD{
    if (_touchIdHUD == nil) {
        _touchIdHUD = [UIAlertController alertControllerWithTitle:@"输入密码" message:@"请输入\"掌上宏力\"的登录密码" preferredStyle:UIAlertControllerStyleAlert];
        [_touchIdHUD addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
            
            textField.secureTextEntry = YES;
        }];
        
        [_touchIdHUD addAction:[UIAlertAction actionWithTitle:@"返回Touch ID" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.touchID startWJTouchIDWithMessage:WJNotice(@"按下HOME键验证指纹信息", @"The Custom Message") fallbackTitle:WJNotice(@"输入密码", @"Fallback Title") delegate:self];
        }]];
        
        [_touchIdHUD addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UITextField *pwdTF = _touchIdHUD.textFields.firstObject;
            if ([pwdTF.text isEqualToString:[User currentUser].password]) {
                _hideView.hidden = YES;
            }else{
                _touchIdHUD.title = @"密码验证失败";
                _touchIdHUD.message = @"请重新输入\"掌上宏力\"的登录密码";
                [self presentViewController:_touchIdHUD animated:YES completion:nil];
            }
            
        }]];

    }
    [self presentViewController:_touchIdHUD animated:YES completion:nil];
}

-(void)setHideViewState:(BOOL)isHide{
    _hideView.hidden = isHide;
    self.tabBarController.tabBar.hidden = !isHide;
}


@end
